import React, { FC, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  Typography,
  Space,
  Form,
  Input,
  Button,
  Checkbox,
  message,
} from "antd";
import { UserAddOutlined } from "@ant-design/icons";
import style from "./login.module.scss";
import { REGISTER_PATHNAME, MANAGE_INDEX_PATHNAME } from "../router";
import { useRequest } from "ahooks";
import { loginServer } from "../services/user";
import { setToken } from "../utils/user-token";

const { Title } = Typography;
const USERNAME = "user";
const PASSWORD = "password";

const Login: FC = () => {
  console.log('login 页面')
  const [form] = Form.useForm(); // antd中form表单的第三方hooks
  const nav = useNavigate();
  useEffect(() => {
    const { user, password } = getUserFormStorage();

    form.setFieldsValue({ user, password });
  }, []);

  // 设置localstorage记住密码
  function remembers(user: string, password: string) {
    localStorage.setItem(USERNAME, user);
    localStorage.setItem(PASSWORD, password);
  }
  // 忘记密码
  function removeFormStorage() {
    localStorage.removeItem(USERNAME);
    localStorage.removeItem(PASSWORD);
  }
  // 获取storage中的值
  function getUserFormStorage() {
    return {
      user: localStorage.getItem(USERNAME),
      password: localStorage.getItem(PASSWORD),
    };
  }

  const { run, loading } = useRequest(
    async (value) => {
      const { username, password } = value;
      return await loginServer(username, password);
    },
    {
      manual: true,
      onSuccess(result) {
        const {token = ""} = result
        message.success("登陆成功");
        // 存储token
        setToken(token)
        // 导航到我的问卷页面
        nav(MANAGE_INDEX_PATHNAME);
        console.log('============= 登陆后，进入list  ==================')
      },
    }
  );

  const onFinish = (value: any) => {
    console.log("form value", value);
    run(value);
    const { user, password } = value;
    if (value.remember) {
      // 记录
      remembers(user, password);
    } else {
      removeFormStorage();
    }
  };

  return (
    <div className={style.container}>
      <div className="1">
        <Space>
          <Title>
            <UserAddOutlined />
          </Title>
          <Title level={2}>用户登陆</Title>
        </Space>
      </div>
      <div className="2">
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 160 }}
          onFinish={onFinish}
          style={{ minWidth: "500px" }}
          initialValues={{ remember: true }}
          form={form}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: "请输入用户名" },
              { type: "string", min: 5, max: 20, message: "用户名长度在5-20" },
              { pattern: /^\w+$/, message: "用户名只能是数字、字母、_" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item name="password" label="密码">
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{ offset: 8, span: 16 }}
          >
            <Checkbox checked>记住我</Checkbox>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 20, offset: 10 }}>
            <Space>
              <Button htmlType="submit" type="primary">
                登陆
              </Button>
              <Link to={REGISTER_PATHNAME}>注册新用户</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
